<template>
  <div class="scrollMenu" ref="scrollMenu">
    <div class="content">
      <div class="left" ref="left">
        <ul>
          <li v-for="(item,index) in items" :key="index" :class="[{active:index == currentIndex}]" @click="scrollTo(index)">
            <span v-text="item.NAME"></span>
            <span v-if="selectedTypeListNumShow(item.GOODSTYPE_ID)" class="tips">
              <badge :text="selectedTypeListNumShow(item.GOODSTYPE_ID)"></badge>
            </span>
          </li>
        </ul>
      </div>
      <div class="right" ref="right">
        <ul>
          <li v-for="(item,index) in items" :key="index">
            <div class="class-title" v-text="item.NAME"></div>
            <div class="itemWrap" v-for="goodItem in item.list">
              <div class="item">
                <div class="item-left">
                  <a class="imgPlaceHolder" v-if="goodItem.IMAGE == ''"></a>
                  <a v-else class="img"><img :src="imgPath + goodItem.IMAGE" :onerror="defaultImg" /></a>
                </div>
                <div class="item-right">
                  <div class="titlePlaceHolder" :class="[{title:goodItem.NAME != ''}]"><span v-text="goodItem.NAME"></span></div>
                  <div class="subtitlePlaceHolder" :class="[{subtitle:goodItem.NAME != ''}]"></div>
                  <div class="pricePlaceHolder" v-if="goodItem.PRICE == 0"></div>
                  <div class="price" v-else>¥ <span v-text="formatCurrency(goodItem.PRICE)"></span> 元</div>
                </div>
                <div class="item-num">
                  <span v-if="multiSpecOrNot(goodItem)">
                    <x-button @click.native="openMultiSpecPopUp(goodItem)" mini type="default" class="chooseMultiSpecBtn">选规格</x-button>
                    <span v-if="selectedNumShow(goodItem.GOODS_ID)" class="tips">
                      <badge :text="selectedNumShow(goodItem.GOODS_ID)"></badge>
                    </span>
                  </span>
                  <span v-else>
                    <i class="iconfont icon-minuscircle minus" v-if="selectedNumShow(goodItem.GOODS_ID)" @click="minusNumber(goodItem)"></i>
                    <span class="numText" v-if="selectedNumShow(goodItem.GOODS_ID)" v-text="selectedNumShow(goodItem.GOODS_ID)"></span>
                    <i class="iconfont icon-xinzeng add" @click="addNumber(goodItem)"></i>
                  </span>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="bottom" ref="bottom">
        <div class="leftPart">
          <div class="shoppingCarBtn">
            <a @click="openShoppingCarPopUp">
              <i class="iconfont icon-gouwuche" :class="[{notEmpty:selectItems.length > 0}]"></i>
            </a>
          </div>
          <p class="countText" v-if="selectItems.length > 0">
            <span class="countUp">已选 <span v-text="countUp"></span> 件商品，</span><br/>
            共计 <b style="color:#FF5556;">¥ <span v-text="formatCurrency(addUp)"></span></b> 元
          </p>
          <p class="countTextEmpty" v-else>购物车是空的</p>
        </div>
        <div class="rightPart">
          <a @click="toPay" class="toPayBtn" :class="[{notEmpty:selectItems.length > 0}]">结 算</a>
        </div>
      </div>
    </div>
    <popup v-model="showShoppingCar" :popup-style="{zIndex:501}" position="bottom" max-height="65%" class="shoppingCarPop" ref="shoppingCarPop">
      <div class="topInfo" ref="topInfo">
        已选商品：<span v-text="countUp"></span>件
        <a class="clearSelected" @click="clearSelected"><i class="iconfont icon-lajitong"></i>清空</a>
      </div>
      <div class="selectedList" ref="selectedList">
        <div class="selectedListWrap">
          <div v-for="(item,index) in selectItems" :key="index" class="item">
            <div class="item-content">
              <h5>
                <span class="title" v-text="item.NAME"></span>
                <small class="matchDrink" v-if="item.MATCHINGDRINK.replace(/\s+/g,'') != ''" v-text="'[ 配饮：' + item.choosenMatchingDrink.MATCHINGDRINK_NAME + ' X ' + item.choosenMatchingDrink.MATCHINGDRINK_NUM + ' ]'"></small>
              </h5>
              <div class="setMeal" v-if="item.choosenMealSetItems && item.choosenMealSetItems.length > 0">
                已选套餐内容：
                <span class="setMealItem" v-for="(sMitem,sMIndex) in item.choosenMealSetItems" :key="sMIndex">
                  <span v-text="sMitem.NAME"></span>&nbsp;X&nbsp;<span v-text="sMitem.QUANTITY + sMitem.UNIT"></span> /
                </span>
              </div>
              <div class="price">¥ <span v-text="formatCurrency(item.QUANTITY*item.PRICE)"></span> 元</div>
            </div>
            <div class="item-num">
              <x-icon class="minus" type="ios-minus-outline" size="28" @click="minusNumber(item)"></x-icon>
              <span class="numText" v-text="item.QUANTITY"></span>
              <x-icon class="add" type="ios-plus-outline" size="28" @click="addNumber(item)"></x-icon>
            </div>
          </div>
          <br/>
        </div>
      </div>
    </popup>
    <popup v-model="showMultiSpec" @on-hide="clearMultiSpecStatus" :popup-style="{zIndex:503}" position="bottom" :height="'80%'" class="multiSpecPop" ref="multiSpecPop">
      <div class="specText" ref="specText">
        <h5 v-text="clickedItem.NAME"></h5>
        <small>
          <div v-if="clickedItem.MATCHINGDRINK && clickedItem.MATCHINGDRINK.replace(/\s+/g,'') != ''" class="choosenMatchDrink">
            已选配饮：<span v-text="getChoosenMatchDrink()"></span>
          </div>
          <div v-if="clickedItem.GOODS_LIST && clickedItem.GOODS_LIST.length > 0" class="choosenMealSet">
            已选套餐：<span v-text="getChoosenMealSet()"></span>
          </div>
        </small>
      </div>
      <div class="specArea" ref="specArea">
        <div class="specAreaWrap">
          <div v-if="clickedItem.MATCHINGDRINK && clickedItem.MATCHINGDRINK.replace(/\s+/g,'') != ''" class="matchDrink">
            配饮：<br/>
            <checker v-model="choosenMatchingDrinkId" @on-change="changeMultiSpec" radio-required default-item-class="checkerItem" selected-item-class="checkerItem-selected">
              <checker-item v-for="(item,index) in JSON.parse(clickedItem.MATCHINGDRINK)" :key="index" :value="item.MATCHINGDRINK_ID" v-html="item.MATCHINGDRINK_NAME"></checker-item>
            </checker>
          </div>
          <div v-if="clickedItem.GOODS_LIST && clickedItem.GOODS_LIST.length > 0" class="mealSet">
            套餐内容({{clickedItem.GOODS_LIST.length}}选{{this.maxChoosenMealSetItem}})：<br/>
            <checker v-model="choosenMealSetItemIds" @on-change="changeMultiSpec" type="checkbox" :max="maxChoosenMealSetItem" default-item-class="checkerItem" selected-item-class="checkerItem-selected">
              <checker-item v-for="(item,index) in clickedItem.GOODS_LIST" :key="index" :value="item.GOODS_ID" v-html="item.NAME"></checker-item>
            </checker>
          </div>
          <div class="chooseSpecBtnWrap">
            <x-button @click.native="addItem" :gradients="['#1D62F0', '#19D5FD']" class="chooseSpecBtn">选好了</x-button>
          </div>
          <br/><br/>
        </div>
      </div>
    </popup>
  </div>
</template>

<script>
  import {InlineXNumber, Popup, XButton, Badge, Checker, CheckerItem, numberComma } from 'vux'
  import {toDecimal2,Trim,message} from "../common/util";
  import {browserAdapt} from "../common/browserAdapt";

  export default {
    name:'scrollMenu',
    data() {
      return {
        currentIndex:0,
        defaultImg:"this.src= '" + require('../assets/images/defaultGoodImg-thumb.jpg') +"'",
        showShoppingCar:false,
        showMultiSpec:false,
        clickedItem:{},
        choosenMatchingDrinkId:'',
        choosenMealSetItemIds:[],
        maxChoosenMealSetItem:1
      }
    },
    components: {
      InlineXNumber,
      Popup,
      XButton,
      Badge,
      Checker,
      CheckerItem
    },
    props: {
      headerHeight:{
        type:Number,
        default:46
      },
      items:{
        type: [Array]
      },
      selectItems:{
        type: [Array]
      },
      imgPath:{
        type:String
      }
    },
    computed: {
      addUp(){
        let total = 0
        for(let item of this.selectItems){
          total = total + item.PRICE*item.QUANTITY
        }
        return total
      },
      countUp(){
        let count = 0
        for(let item of this.selectItems){
          count = count + 1*item.QUANTITY
        }
        return count
      }
    },
    methods: {
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      scrollTo(index){
        //console.log(document.documentElement.scrollTop , document.body.scrollTop , window.pageYOffset)
        // vue中document.documentElement.scrollTop无效，使用document.body.scrollTop或window.pageYOffset
        // 不使用自制动画
        if(browserAdapt(['IOS','Android'])){
          document.body.scrollTop = this.$refs.right.children[0].children[index].offsetTop + 5
        }else{
          document.documentElement.scrollTop = this.$refs.right.children[0].children[index].offsetTop + 5
        }
        // 使用自制动画(IOS底下有卡顿问题)
        /*let interval = setInterval(()=>{
          //console.log(this.currentIndex,index)
          if(this.currentIndex < index){
            //console.log(1,document.body.scrollHeight,document.body.scrollTop,this.$refs.right.children[0].children[index].offsetTop)
            if(document.body.scrollTop <= this.$refs.right.children[0].children[index].offsetTop){
              let outHeight = window.screen.height - (this.$refs.bottom.offsetHeight + this.headerHeight)
              for(var i = index; i >= 0; i--){
                //console.log(13,this.$refs.right.children[0].offsetHeight - this.$refs.right.children[0].children[i].offsetTop,outHeight)
                if(this.$refs.right.children[0].offsetHeight - this.$refs.right.children[0].children[i].offsetTop > outHeight){index = i;break}
              }
              document.body.scrollTop = document.body.scrollTop + 10
            }else{
              clearInterval(interval)
            }
          }else if(this.currentIndex >= index){
            //console.log(2,document.body.scrollHeight,document.body.scrollTop-10,this.$refs.right.children[0].children[index].offsetTop)
            if(document.body.scrollTop-10 > this.$refs.right.children[0].children[index].offsetTop){
              document.body.scrollTop = document.body.scrollTop - 10
            }else{
              clearInterval(interval)
            }
          }
        },0)*/
      },
      multiSpecOrNot(item){
        if((item.MATCHINGDRINK == undefined || Trim(item.MATCHINGDRINK,'g') == '') && (!item.GOODS_LIST || item.GOODS_LIST.length <= 0))
          return false//判断为单品商品
        else return true
      },
      getChoosenMatchDrink(){
        let name = ''
        JSON.parse(this.clickedItem.MATCHINGDRINK).some(item =>{
          if(item.MATCHINGDRINK_ID == this.choosenMatchingDrinkId){
            name = item.MATCHINGDRINK_NAME
            return true
          }
        })
        return name
      },
      getChoosenMealSet(){
        let name = ''
        for(let choosenId of this.choosenMealSetItemIds){
          this.clickedItem.GOODS_LIST.some(item =>{
            if(item.GOODS_ID == choosenId){
              name += item.NAME + ' / '
              return true
            }
          })
        }
        return name
      },
      openMultiSpecPopUp(item){
        this.clickedItem = item
        let tempMax = item.GOODS_LIST && item.GOODS_LIST.length > 0?item.GOODS_LIST.length:0
        this.maxChoosenMealSetItem = (item.PICK_MAX_NUM && item.PICK_MAX_NUM > 0)?item.PICK_MAX_NUM:tempMax
        if(item.GOODS_LIST && item.GOODS_LIST.length > 0){//判断为套餐商品，显示弹出框套餐内容
          if(this.maxChoosenMealSetItem == item.GOODS_LIST.length){//判断必选项是否等于商品列表
            for(let goodItem of item.GOODS_LIST){
              this.choosenMealSetItemIds.push(goodItem.GOODS_ID)
            }
          }
        }
        if(item.MATCHINGDRINK && item.MATCHINGDRINK.replace(/\s+/g,"") != ''){//判断为有配饮商品，显示弹出框配饮内容
          this.choosenMatchingDrinkId = JSON.parse(item.MATCHINGDRINK)[0].MATCHINGDRINK_ID
        }
        this.changeMultiSpec()
        this.setSpecSize()
        this.showMultiSpec = !this.showMultiSpec
      },
      changeMultiSpec(){
        this.$emit('change-multi-spec',{
          choosenMatchingDrinkId:this.choosenMatchingDrinkId,
          choosenMealSetItemIds:this.choosenMealSetItemIds
        })
        this.setSpecSize()
      },
      clearMultiSpecStatus(){
        this.showMultiSpec = false
        this.clickedItem = {}
        this.choosenMatchingDrinkId = ''
        this.choosenMealSetItemIds = []
        this.$emit('clear-choosen-multi-spec')
        this.maxChoosenMealSetItem = 1
      },
      addItem(){//点击选择的按钮
        let flag = true
        if(this.clickedItem.GOODS_LIST && this.clickedItem.GOODS_LIST.length > 0 && this.choosenMealSetItemIds.length < this.maxChoosenMealSetItem){
          message({message:'请选择'+this.maxChoosenMealSetItem+'个套餐商品',type:'error'})
          flag = false
        }else if(this.clickedItem.MATCHINGDRINK && this.clickedItem.MATCHINGDRINK.replace(/\s+/g,'') != ''){
          if( this.choosenMatchingDrinkId == ''){
            message({message:'请选择配饮',type:'error'})
            flag = false
          }
        }
        if(flag){
          this.addNumber(this.clickedItem)
          this.clearMultiSpecStatus()
        }
      },
      addNumber(item){
        this.$emit('add-number',item)
      },
      minusNumber(item){
        if(this.countUp <= 1) this.showShoppingCar = false
        this.$emit('minus-number',item)
      },
      selectedNumShow(goodId){
        let returnNum = false
        this.selectItems.forEach(item =>{
          if(item.GOODS_ID == goodId && item.QUANTITY > 0){
            returnNum += item.QUANTITY
          }
        })
        return returnNum
      },
      selectedTypeListNumShow(typeId){
        let returnNum = false
        this.items.some(typeItem =>{
          if(typeItem.GOODSTYPE_ID == typeId){
            this.selectItems.forEach(selectGoodItem =>{
              typeItem.list.forEach(goodItem =>{
                if(goodItem.GOODS_ID == selectGoodItem.GOODS_ID){
                  returnNum += selectGoodItem.QUANTITY
                }
              })
            })
            return true
          }
        })
        return returnNum
      },
      toPay(){
        this.$emit('to-pay')
      },
      openShoppingCarPopUp(){
        setTimeout(()=>{
          if(this.selectItems.length <= 3)
            this.$refs.selectedList.style.height = ''
          else
            this.$refs.selectedList.style.height = (this.$refs.shoppingCarPop.$el.offsetHeight - this.$refs.topInfo.offsetHeight -20) + 'px'
        },10)
        if(this.selectItems.length > 0)this.showShoppingCar = !this.showShoppingCar
        else message({message:'购物车为空',type:'info'})
      },
      clearSelected(){
        this.showShoppingCar = false
        this.$emit('clear-selected')
      },
      setSpecSize(){
        setTimeout(()=>{
          this.$refs.specArea.style.height = (this.$refs.multiSpecPop.$el.offsetHeight - this.$refs.specText.offsetHeight -20) + 'px'
        },10)
      }
    },
    mounted(){
      setTimeout(()=>{
        this.$refs.left.style.top = this.headerHeight + 'px'
        this.$refs.left.children[0].style.paddingBottom = this.headerHeight + 'px'
      },10)
      window.onscroll = ()=> {
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        let rightLis = this.$refs.right.children[0].children
        //console.log(scrollTop,this.headerHeight)
        /*if(scrollTop >= this.headerHeight){
          this.$refs.left.style.position = 'fixed'
          this.$refs.right.style.marginLeft = this.$refs.left.offsetWidth + 'px'
        }else{
          this.$refs.left.style.position = 'relative'
          this.$refs.right.style.marginLeft = '0px'
        }*/
        for(let i = (rightLis.length - 1); i >= 0; i--){
          if(scrollTop > rightLis[i].offsetTop){
            //console.log(scrollTop,rightLis[i].offsetTop,i)
            this.currentIndex = i
            break
          }
        }
      }
    },
    beforeDestroy(){
      window.onscroll = ()=> {}
    }
  }
</script>

<style lang="scss" scoped>
  .scrollMenu{
    .content{
      width: 100%;overflow: hidden;position: relative;
      .left{
        overflow: auto;top: 0;width: 25%;height: 100%;background: #eee;position: fixed;z-index:100;
        ul{
          list-style: none;margin-bottom: 3rem;
          li{
            padding: 0.9rem 0.5rem;text-align: center;position: relative;
            &.active{background: #fff;border-left: 2px solid #FF5556;}
            .tips{position: absolute;right: 0.4rem;top: 0;}
          }
        }
      }
      .right{
        float: left;width: 75%;height: 100%;padding-bottom: 3rem;margin-left: 25%;position: relative;z-index:50;
        ul{
          list-style: none;
          li{
            .class-title{padding: 0.5rem 1rem;background: #eee;}
            .itemWrap{
              background: #fff;
              .item{
                position: relative; display:flex;overflow: hidden;width: 94%;padding: 0.65rem 3%; background: #fff;border-bottom: 1px solid #eee;
                .item-left{
                  font-size: 0;
                  line-height: 1;width: 5rem;height: 5rem;margin-right: 0.5rem;
                  .imgPlaceHolder{display:block;background: #eee;width: 100%;height: 100%;}
                  .img{
                    img{width: 100%;height: 100%;}
                  }
                }
                .item-right{
                  -webkit-box-flex: 1;-webkit-flex: 1;flex: 1;font-size: .9rem;color: #666;
                  .titlePlaceHolder{width: 100%;height: 1.3rem;background: #eee;}
                  .subtitlePlaceHolder{width: 75%;height: 1.3rem;margin-top: 0.6rem;background: #eee;}
                  .pricePlaceHolder{width: 55%;height: 1.3rem;margin-top: 0.5rem;background: #eee;}
                  .title{width: 100%;line-height:1.5rem;height:auto;background:none;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}
                  .subtitle{display: none;}
                  .price{width: 55%;height:auto;background:none;margin-top: 0.5rem;}
                }
                .item-num{
                  position: absolute;right: 3.5%;bottom: 0.6rem;
                  .iconfont{font-size: 1.6rem;color: #ffa000;vertical-align: middle;}
                  .chooseMultiSpecBtn{padding:0 0.6rem;font-size: 0.7rem;color:#fff;border-radius: 1rem;border-color:#ffa000;background-color:#ffa000;border-image-width: 0;}
                  .numText{display:inline-block;width:1.3rem;text-align:center;}
                  .tips{position: absolute;top:-0.6rem;right:-0.2rem;}
                }
              }
            }
          }
        }
      }
      .bottom{
        height: 3rem;width: 100%;background: #fff;position:fixed;bottom:0;left:0;z-index: 502;display: flex;border-top: 1px solid #dfdfdf;
        .leftPart{
          flex-grow: 3;display:flex;
          .shoppingCarBtn{
            margin:-1rem 0 0  0.5rem;
            a{
              i{
                font-size: 3.5rem;color: #dddede;
                &.notEmpty{color:#FF5556;}
              }
            }
          }
          .countText{
            margin:0.2rem 0 0 0.5rem;line-height: 1.2rem;
            .countUp{font-size: 0.9rem;color: #8f8f8f;}
          }
          .countTextEmpty{margin-left:0.5rem;line-height: 3rem;}
        }
        .rightPart{
          flex-grow: 1;min-width: 25%;
          .toPayBtn{
            background-color: #dddede;color:#fff;width:100%;height:100%;display:flex;flex-direction:column;justify-content:center;text-align:center;
            &.notEmpty{background-color:#FF5556;}
          }
        }
      }
    }
    .shoppingCarPop{
      bottom: 3rem;padding:0 3%;width: 94%;overflow: hidden;
      .topInfo{
        color: #939393;position: relative;padding:0.6rem 0 0.7rem;
        .clearSelected{
          color: #939393;position: absolute;right: 0;top:0.6rem;
          i{font-size: 1.3rem;}
        }
      }
      .selectedList{
        overflow: hidden;margin-bottom: 20px;
        .selectedListWrap{
          height: 100%;overflow: auto;background-color: #fff;
          .item{
            position: relative; display:flex;overflow: hidden;width: 94%;padding: 0.65rem 3%; background: #fff;border-bottom: 1px solid #eee;
            .item-content{
              -webkit-box-flex: 1;-webkit-flex: 1;flex: 1;font-size: .9rem;color: #666;
              .titlePlaceHolder{width: 100%;height: 1.3rem;background: #eee;}
              .subtitlePlaceHolder{width: 75%;height: 1.3rem;margin-top: 0.6rem;background: #eee;}
              .pricePlaceHolder{width: 55%;height: 1.3rem;margin-top: 0.5rem;background: #eee;}
              h5{
                overflow: hidden;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;
                .title{color: #313131;font-size: 0.9rem;width: 100%;line-height:1.3rem;height:auto;background:none;}
                small.matchDrink{color: #7e7e7e;}
              }
              .setMeal{
                font-size: 0.8rem;color: #7e7e7e;margin-top: 0.3rem;
                .setMealItem{}
              }
              .subtitle{display: none;}
              .price{width: 55%;height:auto;background:none;margin-top: 0.5rem;}
            }
            .item-num{
              position: absolute;right: 3%;bottom: 0.35rem;
              span.numText{vertical-align: super;}
            }
          }
        }
      }
    }
    .multiSpecPop{
      padding:0 3%;width: 94%;overflow: hidden;
      .specText{
        padding:0.6rem 0 0.7rem;
        h5{font-size: 1rem;font-weight: bold;}
        small{color: #939393;}
      }
      .specArea{
        position:relative;height:50%;overflow: hidden;margin-bottom: 20px;
        .specAreaWrap{
          height: 100%;background: #fff;overflow: auto;width: 94%;padding: 0.65rem 3%;
          .matchDrink{margin-bottom: 20px;}
          .mealSet{margin-bottom: 20px;}
          .vux-checker-box{
            padding:0.5rem 0;
            display: flex;flex-wrap:wrap;
            .checkerItem {margin: 0 2.3% 0.5rem 0;width: 28%;min-height: 42px;line-height:1rem;font-size: 0.8rem;
              display: flex;justify-content: center;align-items: center;padding:0.3rem 1.2%;
              text-align: center;border-radius: 3px;border: 1px solid #ccc;background-color: #fff;}
            .checkerItem-selected {background: #ffffff url(../assets/images/checker/active.png) no-repeat right bottom;border-color: #ff4a00;}
          }
          .chooseSpecBtnWrap{position: absolute;bottom:0;left: 0;padding: 0.5rem 3%;width: 94%;background-color: #fff;}
        }
      }
    }
  }
</style>
